import { useHistory, useLocation } from 'react-router-dom'
import { NavBar, InfiniteScroll } from 'antd-mobile'
import { useRef } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import styles from './index.module.scss'
import { getSearchResult } from '@/store/actions/search'
import { RootState } from '@/types/store'
import ArticleItem from '@/pages/Home/components/ArticleItem'

const SearchResult = () => {
  const history = useHistory()
  const location = useLocation()
  const dispatch = useDispatch()
  // 路由参数
  const params = new URLSearchParams(location.search)
  const keyword = params.get('key')!
  // const keyword = decodeURI(location.search.replace('?keyword=', ''))

  const { results = [] } = useSelector((state: RootState) => state.search.results)

  // useEffect(() => {
  //   dispatch(getSearchResult(keyword, 1))
  // }, [dispatch, keyword])

  const hasMore = results.length < 100
  const pageRef = useRef(1)
  // 加载更多
  const loadMore = async () => {
    await dispatch(getSearchResult(keyword, pageRef.current))
    pageRef.current++
  }
  return (
    <div className={styles.root}>
      <NavBar onBack={() => history.go(-1)}>搜索结果</NavBar>
      <div className="article-list">
        {
          results.map(item => (
            <div className="article-item" key={item.art_id}>
              <ArticleItem article={item}></ArticleItem>
            </div>
          ))
        }
        <InfiniteScroll hasMore={hasMore} loadMore={loadMore}></InfiniteScroll>
      </div>
    </div>
  )
}

export default SearchResult
